package com.flutter.teach.flutter_view

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.annotation.NonNull
import com.flutter.teach.flutter_teach.R
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.platform.PlatformView

/**
 * 描述:
 * 作者:liuhaichao
 * 创建日期：2023/4/11 on 1:10 PM
 */
class MyAndroidView(context: Context, messenger: BinaryMessenger, viewId: Int, creationParams: Map<String, Any?>?) : PlatformView {

    private val view: View
    private val tvMessage: TextView
    private val sendButton: Button
    private val methodChannel: MethodChannel

    init {
        view = LayoutInflater.from(context).inflate(R.layout.view_android, null)
        tvMessage = view.findViewById(R.id.tvMessage)
        sendButton = view.findViewById(R.id.sendButton)
        tvMessage.text = creationParams?.get("initText")?.toString() ?: ""

        methodChannel = MethodChannel(messenger, "pluginChannel")
        methodChannel.setMethodCallHandler { call: MethodCall, result: MethodChannel.Result ->
            when (call.method) {
                "plugin" -> {
                    tvMessage.text = call.arguments() ?: ""
                    result.success("Android received")
                }

                else -> {
                    result.notImplemented()
                }
            }
        }
        sendButton.setOnClickListener {
            methodChannel.invokeMethod("plugin", "send from Android", object : MethodChannel.Result {
                override fun success(result: Any?) {
                    tvMessage.text = result?.toString() ?: ""
                }

                override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) {
                }

                override fun notImplemented() {
                }

            })
        }
    }

    override fun getView(): View {
        return view
    }

    override fun dispose() {
    }
}